<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <button id="btn1">发消息</button>
  <button id="btn2">断开连接</button>
  <script>
    // 1. 通过websocket 建立连接
    const ws = new WebSocket('wss://javascript.info/article/websocket/demo/hello')
    // 2. 监听连接成功
    ws.onopen = () => {
      console.log('连接成功');
    }
    // 3. 如何发消息 ws.send('发送的消息')
    document.querySelector('#btn1').addEventListener('click', function() {
      ws.send('hello websocket!!!')
    })
    // 4. 如何接收消息
    ws.onmessage = (msg) => {
      console.log('服务器返回的消息', msg);
    }

    document.querySelector('#btn2').addEventListener('click', function() {
      ws.close() // 主动断开
    })
    // 5. 如何监听连接断开
    ws.onclose = () => {
      console.log('连接断开');
    }

  </script>
</body>
</html>